package com.wang.jmonkey.ca.handler.login.success;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.wang.jmonkey.common.constant.SecurityConstant;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 获取token信息
 * @Author HeJiawang
 * @Date 2021/5/14 14:28
 */
@Component
public class TokenBuildHandlerManager implements TokenBuildHandlerAdapter {

    private ApplicationContext context;

    private List<TokenBuildHandlerAdapter> list = new ArrayList<>();

    public TokenBuildHandlerManager(ApplicationContext context) {
        this.context = context;
    }

    @PostConstruct
    private void init() {
        Map<String, TokenBuildHandlerAdapter> map = context.getBeansOfType(TokenBuildHandlerAdapter.class);
        if (CollUtil.isEmpty(map)) return;

        map.entrySet().forEach(entry -> {
            if ( !(entry.getValue() instanceof TokenBuildHandlerManager) ) {
                list.add(entry.getValue());
            }
        });
    }

    @Override
    public OAuth2AccessToken handler(HttpServletRequest request, Authentication authentication) {
        if (CollUtil.isEmpty(list)) return null;

        String oauthType = StrUtil.toString(request.getAttribute(SecurityConstant.LoginParameter.oauthType.getKey()));
        for (TokenBuildHandlerAdapter adapter : list) {
            if (adapter.support(oauthType)) {
                return adapter.handler(request, authentication);
            }
        }

        return null;
    }

    @Override
    public boolean support(String oauthType) {
        return false;
    }

}
